package com.simple.base.core.service.impl;

import com.simple.base.common.enums.MenuType;
import com.simple.base.core.domain.response.SysMenuResponse;
import com.simple.base.core.repository.entity.SysMenu;
import com.simple.base.core.repository.entity.extend.SysMenuExtend;
import com.simple.base.core.repository.mapper.SysMenuMapper;
import com.simple.base.core.service.ISysMenuService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单信息表 服务实现类
 * </p>
 *
 * @author kin
 * @since 2017-12-19
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    @Override
    public List<SysMenuExtend> getUserMenuList(Long userId) {
       return getAllMenuList(userId);
    }


    /**
     * 获取所有菜单列表
     */
    private List<SysMenuExtend> getAllMenuList(Long userId) {
        List<SysMenuExtend> menuItemList = baseMapper.queryUserList(userId);

        //查询根菜单列表
        List<SysMenuExtend> parentMenuList = menuItemList.stream().filter(x -> x.getParentId() == 0).collect(Collectors.toList());
        //递归获取子菜单
        getMenuTreeList(parentMenuList, menuItemList);

        return parentMenuList;
    }

    /**
     * 递归
     */
    private List<SysMenuExtend> getMenuTreeList(List<SysMenuExtend> menuList, List<SysMenuExtend> menuItemList) {
        List<SysMenuExtend> subMenuList = new ArrayList<>();

        for (SysMenuExtend entity : menuList) {
            if (entity.getType() == MenuType.CATALOG.getValue()) {//目录
                List<SysMenuExtend> parentMenuList = menuItemList.stream().filter(x -> Objects.equals(x.getParentId(), entity.getId())).collect(Collectors.toList());

                entity.setList(getMenuTreeList(parentMenuList, menuItemList));
            }
            subMenuList.add(entity);
        }

        return subMenuList;
    }
}
